﻿#region License
/* Copyright (c) 2011 Maksymilian Mulawa
	
Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice, 
 * this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright notice, 
 * this list of conditions and the following disclaimer in the documentation 
 * and/or other materials provided with the distribution.
   3. The name of the author may not be used to endorse or promote products 
 * derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using ReplicationExplorer.DomainModel.Distributor.Entities;
using ReplicationExplorer.DomainModel.Distributor.Models;
using ReplicationExplorer.DomainModel.Infrastructure;
using ReplicationExplorer.DomainModel.UI;
using ReplicationExplorer.Presentation.ViewModel;
using ReplicationExplorer.Properties;
using ReplicationExplorer.UserControls;

namespace ReplicationExplorer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly DistributorAggregator _aggregator;

        public MainWindow()
        {
            InitializeComponent();
            _aggregator = new DistributorAggregator();
        }
        
        private void connectToDistributorBtn_Click(object sender, RoutedEventArgs e)
        {
            ConnectDialog dialog = new ConnectDialogFactory().Create(this);
            dialog.ShowDialog();
            if(dialog.DialogResult == true)
            {
                AddDistributor(dialog);
            }
        }

        public void AddDistributor(ConnectDialog dialog)
        {

            bool distributorAlreadyOnTheList = false;

            if (Settings.Default.DistributorList == null)
            {
                Settings.Default.DistributorList = new StringCollection();
            }

            if (Settings.Default.DistributorList.Cast<string>().Any(
                distributorName => distributorName.Equals(
                    dialog.ServerInfo.ServerName, 
                    StringComparison.InvariantCultureIgnoreCase
                    ))
                )
            {
                distributorAlreadyOnTheList = true;
            }

            if (!distributorAlreadyOnTheList)
            {
                Settings.Default.DistributorList.Insert(0, dialog.ServerInfo.ServerName);
            }
            
            DistributorServer distributorServer = dialog.Distributor;
            if (!_aggregator.ExistsDistributor(distributorServer.Server))
            {
                _aggregator.AddDistributor(distributorServer);
                tvObjectExplorer.DataContext = new ObjectExplorerModelView(_aggregator.DistributorServers);
            }
           
            ObjectExplorerModelView tvDataSource = (ObjectExplorerModelView) tvObjectExplorer.DataContext;
            foreach (DistributorServerViewModel server in tvDataSource.DistributorServers)
            {
                if (server.Name.Equals(distributorServer.Server, StringComparison.InvariantCultureIgnoreCase))
                {
                    server.IsSelected = true;
                }
            }
        }

        private void tvObjectExplorer_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            object selectedItem = ((TreeView) sender).SelectedItem;
            infoPanel.Children.Clear();

            if (selectedItem is TreeViewItemViewModel)
            {
                TreeViewItemViewModel itemViewModel = (TreeViewItemViewModel)selectedItem;
                GenericView element = new GenericView(itemViewModel);
                element.ObjectName = itemViewModel.ModelViewName;
                element.ObjectIconSource = itemViewModel.ModelViewIcon;
                element.ShowPropertySearch = itemViewModel.ShowPropertySearch;
                infoPanel.Children.Add(element);
            }
        }
        
        private void disconnectFromDistributorBtn_Click(object sender, RoutedEventArgs e)
        {
            DistributorServerViewModel selectedDistributor = GetSelectedDistributorNode(tvObjectExplorer);
            if(selectedDistributor != null)
            {
                ObjectExplorerModelView tvDataSource = (ObjectExplorerModelView)tvObjectExplorer.DataContext;
                tvDataSource.RemoveDistributorViewModel(selectedDistributor);
                _aggregator.RemoveDistributor(selectedDistributor);
            }
        }

        private void tvObjectExplorer_PreviewMouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            DistributorServerViewModel selectedDistributor = GetSelectedDistributorNode(sender);
            if(selectedDistributor != null)
            {
                e.Handled = true;  
            }
        }

        private DistributorServerViewModel GetSelectedDistributorNode(object sender)
        {
            TreeView item = sender as TreeView;
            DistributorServerViewModel selectedDistributor = null;
            if (item != null)
            {
                object selectedItem = ((TreeView)sender).SelectedItem;
                if (selectedItem is DistributorServerViewModel)
                {
                    selectedDistributor =  (DistributorServerViewModel) selectedItem;
                }
            }

            return selectedDistributor;
        }

        private void miAbout_Click(object sender, RoutedEventArgs e)
        {
            AboutDialog aboutDialog = new AboutDialog();
            aboutDialog.DataContext = new AboutViewModel("http://replicationexplorer.codeplex.com");
            aboutDialog.ShowDialog();
        }

        private void miExit_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void miSearchTransaction_Click(object sender, RoutedEventArgs e)
        {
            TransactionSearchDialog dialog = new TransactionSearchDialog();
            dialog.ShowDialog();
        }
    }
}
